package com.example.wechat;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ViewHolder> {
    private List<Conversation> conversations;
    private OnItemClickListener listener;
    private SimpleDateFormat dateFormat;

    public ConversationAdapter(List<Conversation> conversations) {
        this.conversations = conversations;
        this.dateFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_conversation, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Conversation conversation = conversations.get(position);
        
        holder.nameView.setText(conversation.getNickname());
        holder.messageView.setText(conversation.getLastMessage());
        holder.timeView.setText(dateFormat.format(conversation.getLastMessageTime()));

        Glide.with(holder.itemView.getContext())
                .load(conversation.getAvatarUrl())
                .placeholder(R.drawable.default_avatar)
                .error(R.drawable.default_avatar)
                .into(holder.avatarView);

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(conversation);
            }
        });
    }

    @Override
    public int getItemCount() {
        return conversations.size();
    }

    public void updateData(List<Moment> moments) {

    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView avatarView;
        TextView nameView;
        TextView messageView;
        TextView timeView;

        ViewHolder(View itemView) {
            super(itemView);
            avatarView = itemView.findViewById(R.id.avatar);
            nameView = itemView.findViewById(R.id.name);
            messageView = itemView.findViewById(R.id.message);
            timeView = itemView.findViewById(R.id.time);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(Conversation conversation);
    }
} 